package com.school.controller.student;

import com.school.model.Student;
import com.school.service.StudentService;
import com.school.service.impl.StudentServiceImpl;
import com.school.util.ResponseJsonUtil;
import com.school.vo.R;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

@WebServlet("/student/insert")
public class InsertController extends HttpServlet {
    StudentService studentService = new StudentServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 插入 数据
        Student student = new Student();
        student.setStunum(req.getParameter("studentNumber"));// 学号：和前端约定好字段名称
        student.setName(req.getParameter("studentName"));// 姓名：和前端约定好字段名称
        student.setSex(req.getParameter("sex"));// 性别：和前端约定好字段名称
        student.setPswd(req.getParameter("studentLogin"));// 密码：和前端约定好字段名称

        // 生日：和前端约定好字段名称  2020-12-02 10：10：00
        // 格式化日期
        String birthday = req.getParameter("birthday");
        SimpleDateFormat format = new SimpleDateFormat("y-M-d");
        if (birthday != null) {
            try {
                student.setBirthday(format.parse(birthday));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        // 调用Service中的方法
        Student res = studentService.insert(student);
        if (res.getId() != null) {
            // json格式传递到前端
            ResponseJsonUtil.write(resp, R.ok());
        } else {
            // json格式传递到前端
            ResponseJsonUtil.write(resp, R.err());
        }
    }
}
